package cn.legend.travel.admin.authorize.dao.persist.repository.impl;

import cn.legend.travel.admin.authorize.pojo.entity.User;
import cn.legend.travel.admin.authorize.pojo.param.UserAddNewParam;
import cn.legend.travel.admin.authorize.pojo.param.UserUpdateParam;
import cn.legend.travel.admin.authorize.pojo.vo.UserLoginInfoVO;
import cn.legend.travel.admin.authorize.pojo.vo.UserStandardVO;
import cn.legend.travel.admin.authorize.dao.persist.mapper.UserMapper;
import cn.legend.travel.admin.authorize.dao.persist.repository.IUserRepository;
import cn.legend.travel.common.pojo.vo.PageData;
import cn.legend.travel.common.util.PageInfoToPageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class UserRepositoryImpl implements IUserRepository {
    private final UserMapper mapper;

    @Override
    public PageData<UserStandardVO> getUserList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return PageInfoToPageDataConverter.convert(new PageInfo<>(mapper.getUserList()));
    }

    @Override
    public int addNew(UserAddNewParam param) {
        User user = new User();
        BeanUtils.copyProperties(param, user);
        return mapper.insert(user);
    }

    @Override
    public int update(UserUpdateParam param) {
        User user = new User();
        BeanUtils.copyProperties(param, user);
        return mapper.updateById(user);
    }

    @Override
    public int update(User user) {
        return mapper.updateById(user);
    }

    @Override
    public int deleteById(Long id) {
        return mapper.deleteById(id);
    }

    @Override
    public UserLoginInfoVO getByUsername(String username) {
        return mapper.getByUsername(username);
    }

    @Override
    public int updateLastLogin(Long id, int loginCount) {
        User user = new User();
        user.setId(id);
        user.setLoginCount(loginCount);
        return mapper.updateById(user);
    }

    @Override
    public User getById(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public List<User> getByRoleId(Long roleId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        return mapper.selectList(wrapper);
    }
}
